//
//  ZDPersonInfoController.m
//  特种车调度
//
//  Created by 陈宇 on 15/8/21.
//
//

#import "ZDPersonInfoController.h"
#import "CAlertView.h"
#import "BMCity.h"
#import "BMHttpTool.h"
#import "BMAccountManager.h"

@interface ZDPersonInfoController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPickerViewDataSource, UIPickerViewDelegate>
{
    NSArray *_allProvinces;
    NSArray *_allCities;
    NSArray *_allDistricts;
}

@property (weak, nonatomic) IBOutlet UIImageView *headerView;
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;

@property (weak, nonatomic) IBOutlet UITextField *oldPhoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (nonatomic, strong) CAlertView *alertView;
@property (nonatomic, strong) NSArray *views;

@property (nonatomic, weak) UITextField *districtTF;
@property (nonatomic, weak) UIPickerView *pickerView;

- (IBAction)cancleAction:(id)sender;
- (IBAction)okAction:(UIButton *)sender;
- (IBAction)codeAction:(UIButton *)sender;

@end

@implementation ZDPersonInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.headerView.layer.cornerRadius = 30.f;
    self.headerView.layer.masksToBounds = YES;
    
    UITextField *districtTF = [UITextField new];
    UIPickerView *inputView = [[UIPickerView alloc] init];
    inputView.delegate = self;
    inputView.dataSource = self;
    districtTF.inputView = inputView;
    districtTF.inputAccessoryView = [[[NSBundle mainBundle] loadNibNamed:@"InputToolbar" owner:self options:nil] firstObject];
    [self.view addSubview:districtTF];
    self.districtTF = districtTF;
    self.pickerView = inputView;
    
    [self initDistrictData];
    
    [self setEmptyData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configuration];
}

- (void)configuration
{
    User *user = [BMAccountManager sharedInstance].user;
    [self.headerView sd_setImageWithURL:[NSURL URLWithString:user.icon]];
    if (![BMUtils isEmptyString:user.name]) {
        [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]].detailTextLabel.text = user.name;
    }
    if (![BMUtils isEmptyString:user.phone]) {
        [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]].detailTextLabel.text = user.phone;
    }
    if (![BMUtils isEmptyString:user.address]) {
        [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]].detailTextLabel.text = user.address;
    }
}

/**
 *  解决uitableview右边detailview懒加载出现的bug
 */
- (void)setEmptyData
{
    for (int i = 0; i < [self.tableView numberOfRowsInSection:1]; i++) {
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:1]];
        cell.detailTextLabel.text = @" ";
    }
}

- (void)initDistrictData
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"areas" ofType:@"plist"];
    _allProvinces = [BMCity objectArrayWithFile:path];
    
    _allCities = [[_allProvinces firstObject] nextArea];
    _allDistricts = [[_allCities firstObject] nextArea];
}

- (NSArray *)views
{
    if (!_views) {
        _views = [[NSBundle mainBundle] loadNibNamed:@"ZDAlertView" owner:self options:nil];
        [self.codeButton setBackgroundImage:[UIImage imageWithColor:kGlobalColor] forState:UIControlStateNormal];
    }
    return _views;
}

- (IBAction)cancleAction:(id)sender {
    [self.alertView dismissAlertViewWithAnimated:YES];
}

- (IBAction)okAction:(UIButton *)sender {
    [self.alertView dismissAlertViewWithAnimated:YES];
    
    if (sender.tag) {
        [self changePhoneTask];
    } else {
        [self changeNameTask];
    }
}

- (IBAction)codeAction:(UIButton *)sender {
    NSString *phone = _phoneTextField.text;
    if (![BMUtils isValidateMobile:phone]) {
        [self showHint:@"请输入有效的新手机号码!"];
        return;
    }
    BMRequest *request = [BMRequest requestWithPath:@"obtainVCode.htm"];
    request.params = @{@"mobile": phone, @"role": kRole};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            BMLog(@"%@", response.rawResult);
            __block int timeout = 60; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                        sender.userInteractionEnabled = YES;
                    });
                }else{
                    int seconds = timeout % 60;
                    NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        //NSLog(@"____%@",strTime);
                        [UIView beginAnimations:nil context:nil];
                        [UIView setAnimationDuration:1];
                        [sender setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                        [UIView commitAnimations];
                        sender.userInteractionEnabled = NO;
                    });
                    timeout--;
                }
            });
            dispatch_resume(_timer);
        } else {
            [self showHint:@"获取验证码失败,请重新获取!"];
        }
    }];
}

- (IBAction)toolbarCancle:(id)sender {
    [self.districtTF resignFirstResponder];
}

- (IBAction)toolbarOK:(id)sender {
    [self.districtTF resignFirstResponder];
    
    [self changeAreaTask];
}

- (CAlertView *)alertView
{
    if (!_alertView) {
        _alertView = [[CAlertView alloc] init];
        _alertView.offHeight = 100.f;
    }
    return _alertView;
}

- (void)changeUserNameAction
{
    self.alertView.contentView = self.views.firstObject;
    [self.alertView show];
}

- (void)changePhoneameAction
{
    self.alertView.contentView = self.views.lastObject;
    [self.alertView show];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section) {
        switch (indexPath.row) {
            case 0:
                [self changeUserNameAction];
                break;
            case 1:
                [self changePhoneameAction];
                break;
            case 2:
                [self.districtTF becomeFirstResponder];
                break;
        }
    } else {
        UIAlertController *alertVC = [UIAlertController new];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *imageVC = [[UIImagePickerController alloc] init];
                imageVC.delegate = self;
                imageVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imageVC animated:YES completion:nil];
            } else {
                [self showHint:@"照相机不可用"];
            }
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"本地上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            UIImagePickerController *imageVC = [[UIImagePickerController alloc] init];
            imageVC.delegate = self;
            imageVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imageVC animated:YES completion:nil];
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = BMColor(245, 245, 247, 1);
    return view;
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info;
{
    weakSelf(self);
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        image = [image fixOrientation];
        __block BMRequest *request = [BMRequest requestWithPath:@"uploadImg.htm"];
        request.uploadData = @{@"icon": UIImageJPEGRepresentation(image, 0.1)};
        [weakSelf showHudWithhint:kDefaultMessage];
        [[BMHttpTool sharedInstance] uploadWith:request finish:^(BMResponse *response, NSError *error) {
            [weakSelf hideHud];
            if (response.status == kResultOK) {
                request = [BMRequest requestWithPath:@"updateIcon.htm"];
                NSString *icon = response.rawResult[@"icon"];
                request.params = @{@"id": @([BMAccountManager sharedInstance].user.ID), @"icon": icon, @"role": kRole};
                [weakSelf showHudWithhint:kDefaultMessage];
                [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
                    [weakSelf hideHud];
                    if (response.status == kResultOK) {
                        User *user = [BMAccountManager sharedInstance].user;
                        user.icon = icon;
                        [BMAccountManager sharedInstance].user = user;
                        [weakSelf.headerView sd_setImageWithURL:[NSURL URLWithString:user.icon]];
                    } else {
                        [weakSelf showHint:@"修改头像失败!"];
                    }
                }];
            } else {
                [weakSelf showHint:@"上传头像失败!"];
            }
        }];
    }];
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return _allProvinces.count;
    } else if (component == 1) {
        return _allCities.count;
    } else {
        return _allDistricts.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return [_allProvinces[row] name];
    } else if (component == 1) {
        return [_allCities[row] name];
    } else {
        return [_allDistricts[row] name];
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textColor = [UIColor darkGrayColor];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setFont:[UIFont systemFontOfSize:14.f]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        BMCity *city = _allProvinces[row];
        _allCities = city.nextArea;
        _allDistricts = [[city.nextArea firstObject] nextArea];
        
        //刷新市
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:NO];
        
        //刷新区
        [pickerView reloadComponent:2]; //选择了第0组，刷新第1组的数据
        [pickerView selectRow:0 inComponent:2 animated:NO];
    } else if (component == 1) {
        BMCity *city = _allCities[row];
        _allDistricts = city.nextArea;
        
        //刷新区
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:2 animated:NO];
    }
}

/**
 *  修改地址
 */
- (void)changeAreaTask
{
    BMCity *selectCity;
    
    if (_allDistricts) {
        selectCity = _allDistricts[[self.pickerView selectedRowInComponent:2]];
    } else {
        selectCity = _allCities[[self.pickerView selectedRowInComponent:1]];
    }
    
    BMRequest *request = [BMRequest requestWithPath:@"updateArea.htm"];
    request.params = @{@"id": @([BMAccountManager sharedInstance].user.ID), @"areaId": @(selectCity.ID), @"role": kRole};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            User *user = [BMAccountManager sharedInstance].user;
            user.address = selectCity.fullName;
            [BMAccountManager sharedInstance].user = user;
            [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]].detailTextLabel.text = user.address;
        } else {
            [self showHint:@"修改地址失败!"];
        }
    }];
}

/**
 *  修改姓名
 */
- (void)changeNameTask
{
    NSString *name = self.nameTextField.text;
    if ([BMUtils isEmptyString:name]) {
        [self showHint:@"姓名不能为空!"];
        return;
    }
    BMRequest *request = [BMRequest requestWithPath:@"updateName.htm"];
    request.params = @{@"id": @([BMAccountManager sharedInstance].user.ID), @"name": name, @"role": kRole};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            User *user = [BMAccountManager sharedInstance].user;
            user.name = name;
            [BMAccountManager sharedInstance].user = user;
            [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]].detailTextLabel.text = user.name;
        } else {
            [self showHint:@"修改姓名失败!"];
        }
    }];
}

/**
 *  修改手机号
 */
- (void)changePhoneTask
{
    
    NSString *oldMobile = self.oldPhoneTextField.text;
    NSString *mobile = self.phoneTextField.text;
    NSString *code = self.codeTextField.text;
    
    if (![BMUtils isValidateMobile:oldMobile] || ![BMUtils isValidateMobile:mobile]) {
        [self showHint:@"请输入有效的手机号"];
        return;
    }
    
    if (code.length != 6) {
        [self showHint:@"请输入6位验证码!"];
        return;
    }
    
    __block BMRequest *request = [BMRequest requestWithPath:@"checkVCode.htm"];
    request.params = @{@"mobile": mobile, @"vCode": code};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            request = [BMRequest requestWithPath:@"updatePhone.htm"];
            request.params = @{@"id": @([BMAccountManager sharedInstance].user.ID), @"oldMobile": oldMobile, @"mobile": mobile, @"role": kRole};
            [self showHudWithhint:kDefaultMessage];
            [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
                [self hideHud];
                if (response.status == kResultOK) {
                    User *user = [BMAccountManager sharedInstance].user;
                    user.phone = mobile;
                    [BMAccountManager sharedInstance].user = user;
                    [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]].detailTextLabel.text = user.phone;
                } else {
                    [self showHint:@"修改地址失败!"];
                }
            }];
        } else {
            [self showHint:@"验证码验证失败!"];
        }
    }];
}

@end
